package com.designoutput.service
{
	import com.designoutput.manager.ResourceManager;
	
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	
	public class ServiceBase extends EventDispatcher
	{
		public static var BASE_SERVICE_URL:String;
		
		private var runningCalls:Dictionary = new Dictionary();
		
		protected function call(serviceName:String, parameters:Object, onComplete:Function = null, onError:Function = null):void {
			var serviceCall:BaseHttpService = new BaseHttpService(BASE_SERVICE_URL + serviceName);
			serviceCall.addEventListener(Event.COMPLETE, serviceCall_completeHandler, false, 0, true);
			serviceCall.addEventListener(ErrorEvent.ERROR, serviceCall_errorEvent, false, 0, true);
			serviceCall.send( parameters );
			
			runningCalls[serviceCall] = { onComplete: onComplete, onError: onError };
		}

		protected function serviceCall_completeHandler(e:Event):void
		{
			var serviceCall:BaseHttpService = e.target as BaseHttpService;
			
			var callData:Object = runningCalls[serviceCall];
			
			if(callData.onComplete)
				callData.onComplete(serviceCall.result);
			
			removeCall(serviceCall);
		}
		
		protected function serviceCall_errorEvent(e:Event):void {
			var serviceCall:BaseHttpService = e.target as BaseHttpService;
			
			var callData:Object = runningCalls[serviceCall];
						
			if(callData.onError){
				var error:ServiceError = new ServiceError(ResourceManager.getValue("rm_service_communication_error"));
				callData.onError(error);
			}

			removeCall(serviceCall);
		}
		
		private function removeCall(serviceCall:BaseHttpService):void {
			serviceCall.removeEventListener(Event.COMPLETE, serviceCall_completeHandler, false);
			serviceCall.removeEventListener(ErrorEvent.ERROR, serviceCall_errorEvent, false);
			
			delete runningCalls[serviceCall];
		}
	}
}